package com.browsesoft.htmlcomponent.field;

import org.w3c.dom.Element;
import javax.servlet.http.HttpServletRequest;
import com.browsesoft.ExtendElement;

public class ImageProcessor extends FieldValueProcessor
{
    /**
     * 签名的图片元素
     */
    private Element imageElement;

    public ImageProcessor()
  {
  }

  /**
   * setFieldValue
   *
   * @param e Element
   * @param value String
   * @param request HttpServletRequest
   */
  public void setFieldValue(Element e, String value, HttpServletRequest request)
  {
    // 设置图片字段值
    if(this.hasImageElement(e)) {
      //清除图片
      Element imagee = this.getImageElement(e);
      imagee.getParentNode().removeChild(imagee);
    }
    //如果值不为空
    if(value != null && !value.equals("")) {
      this.imageElement.setAttribute("src", "../attackment/" + value);
      e.getParentNode().appendChild(this.imageElement.cloneNode(true));
    }
    //设置隐藏域值
    e.setAttribute("value",value);
  }

  /**
   * 是否有图片元素
   */
  private boolean hasImageElement(Element e) {
    Element parent = (Element)e.getParentNode();
    String name = e.getAttribute("name");
    return ExtendElement.findElements(parent, "elementname", name).size() != 0;
  }

  /**
   * 设置配置元素
   */
  public void setConfig(Element config) {
    super.setConfig(config);
    this.imageElement = (Element) this.getImageElement(config).cloneNode(true);
  }

  /**
   * 得到图片元素
   */
  private Element getImageElement(Element e) {
    Element parent = (Element)e.getParentNode();
    String name = e.getAttribute("name");
    return (Element)ExtendElement.findElements(parent, "elementname", name).get(0);
  }

  /**
   * 只读处理什么也不作即可
   */
  public void setReadOnly(Element e, String value)
  {
  }
}
